import math

def is_prime_optimized(n):
    """优化后的素数判断方法"""
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    
    limit = int(math.isqrt(n)) + 1
    for i in range(3, limit, 2):
        if n % i == 0:
            return False
    return True

def find_primes(limit):
    """找出指定范围内的所有素数"""
    primes = []
    for num in range(2, limit + 1):
        if is_prime_optimized(num):
            primes.append(num)
    return primes

def print_primes(primes, primes_per_line=5):
    """按格式打印素数"""
    print(f"\n1~20000范围内的素数共{len(primes)}个：")
    print("=" * 50)
    
    count = 0
    for prime in primes:
        print(f"{prime:8d}", end="")
        count += 1
        if count % primes_per_line == 0:
            print()
    
    if count % primes_per_line != 0:
        print()

if __name__ == "__main__":
    limit = 20000
    primes = find_primes(limit)
    print_primes(primes)
    
    # 显示前10个和最后10个素数
    print(f"\n前10个素数: {primes[:10]}")
    print(f"最后10个素数: {primes[-10:]}")